// 定义消息组件
import {BaseElement, baseStyle, ChatStatus} from "./base.js";

const sendBtnInner = `
 <svg  viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4253" width="24" height="24"><path d="M896 156.8v-3.2c0-3.2-3.2-6.4-3.2-9.6 0 0 0-3.2-3.2-3.2 0-3.2-3.2-3.2-3.2-6.4h-3.2s-3.2 0-3.2-3.2h-3.2-3.2-3.2C867.2 128 864 128 864 128h-3.2-3.2c-3.2 0-3.2 0-6.4 3.2h-3.2l-704 352c-12.8 6.4-19.2 19.2-16 32 3.2 12.8 12.8 25.6 25.6 25.6l192 32h6.4c6.4 0 12.8-3.2 19.2-6.4l278.4-208-195.2 227.2c-3.2 3.2-3.2 6.4-6.4 9.6v265.6c0 16 9.6 28.8 25.6 32h6.4c12.8 0 22.4-6.4 28.8-16l80-144 192 153.6c6.4 3.2 12.8 6.4 19.2 6.4 3.2 0 9.6 0 12.8-3.2 9.6-3.2 19.2-16 19.2-25.6l64-704v-3.2" p-id="4254" ></path>
 </svg>`;

const cancelBtnInner = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
                    <rect x="4" y="4" width="16" height="16" rx="3" fill="white"/>
                </svg>`

const clearBtnInner = `
<svg viewBox="0 0 1024 1024" fill="#aaa" xmlns="http://www.w3.org/2000/svg" width="24" height="24">
    <path d="M899.1 869.6l-53-305.6H864c14.4 0 26-11.6 26-26V346c0-14.4-11.6-26-26-26H618V138c0-14.4-11.6-26-26-26H432c-14.4 0-26 11.6-26 26v182H160c-14.4 0-26 11.6-26 26v192c0 14.4 11.6 26 26 26h17.9l-53 305.6c-0.3 1.5-0.4 3-0.4 4.4 0 14.4 11.6 26 26 26h723c1.5 0 3-0.1 4.4-0.4 14.2-2.4 23.7-15.9 21.2-30zM204 390h272V182h72v208h272v104H204V390z m468 440V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H416V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H202.8l45.1-260H776l45.1 260H672z" p-id="7462"></path>
</svg>`;

/**
 * 聊天操作面板
 */
class ChatOptPanel extends BaseElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.shadowRoot.adoptedStyleSheets = [baseStyle];
    }

    editor = null;
    sendBtn = null;
    settingBtn = null;
    clearBtn = null;
    letterCount = null;//字数统计
    resizeObserver = null;



    onReceive(key, value) {
        switch (key) {
            case "chatInstance":
                this.chatInstance.addChatStatusListener((status) => {
                    this.enableSendBtn(status);
                    this.enableSettingBtn(!!this.chatInstance.config.onSettingClick);
                })
        }
    }


    enableSettingBtn(enable) {
        if (enable) {
            this.settingBtn.classList.remove("hide");
        } else {
            this.settingBtn.classList.add("hide");
        }
    }


    enableSendBtn(status) {
        if (!this.sendBtn) return;

        // 重置按钮状态
        this.sendBtn.disabled = false;
        this.sendBtn.style.opacity = '1';
        this.sendBtn.style.cursor = 'pointer';
        this.sendBtn.classList.remove('disabled', 'cancel');
        switch (status) {
            case ChatStatus.IS_READY:
                // 发送按钮
                this.sendBtn.innerHTML = sendBtnInner;
                break;
            case ChatStatus.IS_RECEIVING:
                // 取消按钮
                this.sendBtn.classList.add('cancel');
                this.sendBtn.innerHTML =  cancelBtnInner;
                break;
            default:
                // 禁用状态的发送按钮
                this.sendBtn.disabled = true;
                this.sendBtn.style.opacity = '0.5';
                this.sendBtn.style.cursor = 'not-allowed';
                this.sendBtn.classList.add('disabled');
                this.sendBtn.innerHTML = sendBtnInner;
        }
    }

    connectedCallback() {
        this.setupEditorHeightObserver();
        this.render();
    }

    disconnectedCallback() {
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
        }
    }

    /**
     * 更新发送按钮状态
     */
    updateState() {
        console.debug("更新btn状态")
        if (this.editor.value.trim() == '') {
            this.sendBtn.classList.remove('active');
        } else {
            this.sendBtn.classList.add('active');
        }
        if (this.editor.value.trim() == '') {
            this.editor.classList.remove('auto-height');
        }
        this.letterCount.innerText = this.editor.value.length;
    }

    setupEditorHeightObserver() {
        this.resizeObserver = new ResizeObserver(entries => {
            for (const entry of entries) {
                const { target } = entry;
                const hasScrollbar = target.scrollHeight > target.clientHeight;
                if (hasScrollbar && target.classList.contains("auto-height") == false) {
                    target.classList.add('auto-height');
                }
            }
        });
    }

    setupEditorEventListener() {
        this.resizeObserver.observe(this.editor);
        this.editor.addEventListener('compositionstart', () => {
            this.editor.isComposing = true;
        });

        this.editor.addEventListener('compositionend', () => {
            this.editor.isComposing = false;
            // 在这里处理输入完成的内容
            this.updateState();
        });
        this.editor.addEventListener('input', (e) => {
            //解决中文输入法触发input
            if (this.editor.isComposing) return;
            //如果内容为空了，去掉 auto-height类名
            this.updateState();
        });
        //监听editor的focus事件，给input-panel添加active样式，blur的时候移除该样式
        this.editor.addEventListener('focus', () => {
            this.shadowRoot.querySelector(".ja_input-panel").classList.add('active');
        });
        this.editor.addEventListener('blur', () => {
            this.shadowRoot.querySelector(".ja_input-panel").classList.remove('active');
        });
        this.editor.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.dispatchMessage();
            }
        });
    }

    setupBtnEventListener() {
        this.sendBtn.addEventListener('click', () => {
            if (this.sendBtn.classList.contains('cancel')) {
                // 触发取消事件
                this.chatInstance.cancelCurrentChat();
            } else {
                this.dispatchMessage();
            }
        });
        this.settingBtn.addEventListener('click', () => {
            this.chatInstance.config?.onSettingClick(this.chatInstance);
        });
        this.clearBtn.addEventListener('click', () => {
            this.showConfirm({title:'清空全部消息', content:'您确定要清空当前会话的所有消息记录吗？此操作无法撤销。',
                confirmText:'确认清空', cancelText:'取消'}).then(confirm => {
                if (confirm) {
                    this.handleClearMessages();
                }
            })
        });


    }

    handleClearMessages() {
        if (!this.chatInstance.config.onClearMsg) return;

        const result = this.chatInstance.config.onClearMsg(this.chatInstance.config.sessionId);

        if (result === true) {
            this.chatInstance.messagePanel.clearAllMessages();
        } else if (result instanceof Promise) {
            result.then(resolvedValue => {
                if (resolvedValue === true) {
                    this.chatInstance.messagePanel.clearAllMessages();
                }
            });
        }
    }

    dispatchMessage() {
        const content = this.editor.value.trim();
        if (!content) return;
        let msg = {
            action: 'request',

            data: {
                role: 'user',
                content: { "text": content },
                // files: files
            }
        }
        const success = this.chatInstance.sendMessage(msg);
        if (success) {
            this.editor.value = "";
            this.letterCount.innerText = 0;
            this.updateState()
        }
    }


    render() {
        this.shadowRoot.innerHTML = `
        <style>
            :host {
                flex-shrink: 0;
                background: #ffffff;
                font-size: 14px;
                tab-size: 4;
                -webkit-text-size-adjust: 100%;
                font-feature-settings: normal;
                font-variation-settings: normal;
                -webkit-tap-highlight-color: transparent;
            }


        </style>
        <div class="ja_input-panel">
            <div class="container">
                <div class="ja_input_wrapper">
                    <div class="extra_btns hide">
                        <input id="file_btn" type="file" class="hide" multiple="" accept=".pdf,.doc,.docx,.txt,.md">
                        <input id="img_btn" type="file" class="hide" multiple="" accept="image/*">
                        <button class="clear_btn fx fx-center hide">
                            ${clearBtnInner}
                        </button>
                    </div>
                    <div class="fx fx-1 fx-center">
                        <textarea placeholder="请输入你的问题..." class="input" ></textarea>
                    </div>
                    <div class="noshrink fx fx-center" style="padding: 0.5rem">
                        <button class="send_btn fx fx-center ">
                            <svg  viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4253" width="24" height="24"><path d="M896 156.8v-3.2c0-3.2-3.2-6.4-3.2-9.6 0 0 0-3.2-3.2-3.2 0-3.2-3.2-3.2-3.2-6.4h-3.2s-3.2 0-3.2-3.2h-3.2-3.2-3.2C867.2 128 864 128 864 128h-3.2-3.2c-3.2 0-3.2 0-6.4 3.2h-3.2l-704 352c-12.8 6.4-19.2 19.2-16 32 3.2 12.8 12.8 25.6 25.6 25.6l192 32h6.4c6.4 0 12.8-3.2 19.2-6.4l278.4-208-195.2 227.2c-3.2 3.2-3.2 6.4-6.4 9.6v265.6c0 16 9.6 28.8 25.6 32h6.4c12.8 0 22.4-6.4 28.8-16l80-144 192 153.6c6.4 3.2 12.8 6.4 19.2 6.4 3.2 0 9.6 0 12.8-3.2 9.6-3.2 19.2-16 19.2-25.6l64-704v-3.2" p-id="4254" fill="#ffffff"></path></svg>
                        </button>
                        <button class="setting_btn hide fx fx-center">
                            <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7562" width="24" height="24"><path d="M512.483556 390.599111a110.933333 110.933333 0 0 0-79.104 32.796445 111.36 111.36 0 0 0-32.796445 79.104c0 29.895111 11.690667 57.912889 32.796445 79.104a111.36 111.36 0 0 0 79.075555 32.796444 111.36 111.36 0 0 0 79.132445-32.796444 111.36 111.36 0 0 0 32.796444-79.075556 111.36 111.36 0 0 0-32.796444-79.132444 110.933333 110.933333 0 0 0-79.104-32.796445z m412.302222 235.52l-65.422222-55.921778c3.128889-19.000889 4.721778-38.4 4.721777-57.685333 0-19.313778-1.592889-38.798222-4.693333-57.713778l65.393778-55.893333a32.028444 32.028444 0 0 0 9.301333-35.185778l-0.910222-2.616889a442.567111 442.567111 0 0 0-79.587556-137.671111l-1.820444-2.133333a32.142222 32.142222 0 0 0-35.100445-9.500445l-81.180444 28.899556a349.184 349.184 0 0 0-99.612444-57.486222l-15.701334-84.906667a32.056889 32.056889 0 0 0-25.799111-25.685333l-2.702222-0.512a450.645333 450.645333 0 0 0-158.805333 0l-2.702223 0.512a32.056889 32.056889 0 0 0-25.770666 25.685333l-15.815111 85.304889a353.479111 353.479111 0 0 0-98.901334 57.287111L207.872 211.797333a32 32 0 0 0-35.100444 9.500445l-1.792 2.104889a445.923556 445.923556 0 0 0-79.587556 137.699555l-0.910222 2.588445c-4.494222 12.515556-0.796444 26.510222 9.301333 35.214222l66.190222 56.490667c-3.100444 18.801778-4.608 38.001778-4.608 57.002666 0 19.2 1.507556 38.4 4.608 57.002667l-65.991111 56.490667a32.028444 32.028444 0 0 0-9.301333 35.214222l0.910222 2.588444a443.648 443.648 0 0 0 79.587556 137.699556l1.792 2.104889a32.142222 32.142222 0 0 0 35.100444 9.500444l81.806222-29.098667a346.282667 346.282667 0 0 0 98.901334 57.315556l15.815111 85.276444a32.056889 32.056889 0 0 0 25.770666 25.713778l2.702223 0.512c52.536889 9.443556 106.296889 9.443556 158.805333 0l2.702222-0.512a32.085333 32.085333 0 0 0 25.799111-25.713778l15.701334-84.878222a351.516444 351.516444 0 0 0 99.612444-57.514666l81.180445 28.899555a31.971556 31.971556 0 0 0 35.100444-9.500444l1.820444-2.104889a445.923556 445.923556 0 0 0 79.587556-137.671111l0.910222-2.616889a32.284444 32.284444 0 0 0-9.500444-34.986667z m-412.302222 52.195556a175.786667 175.786667 0 1 1 0-351.601778 175.786667 175.786667 0 1 1 0 351.573333z" fill="#000000" fill-opacity=".65" p-id="7563"></path></svg>
                        </button>
                    </div>
                </div>
            </div>
            <div class="hide"><span class="letter_count ">0</span>/1000</div>
        </div>


    `;

        this.editor = this.shadowRoot.querySelector('.input');
        this.letterCount = this.shadowRoot.querySelector('.letter_count');
        this.setupEditorEventListener()
        this.sendBtn = this.shadowRoot.querySelector('.send_btn');
        this.settingBtn = this.shadowRoot.querySelector('.setting_btn');
        this.clearBtn = this.shadowRoot.querySelector('.clear_btn');
        this.setupBtnEventListener();

        // Remove hide class from extra_btns if showClearMsgBtn is true
        setTimeout(() => {
            if (this.chatInstance?.config?.showClearMsgBtn && this.chatInstance?.config?.onClearMsg) {
                this.shadowRoot.querySelector('.extra_btns').classList.remove('hide');
                this.clearBtn.classList.remove('hide');
            }
        }, 100)
    }
}

export default ChatOptPanel;